package com.example.admin.goodnews.fragment.DiQuXinWen;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.admin.goodnews.R;
import com.example.admin.goodnews.activity.ChangeCityActivity;
import com.example.admin.goodnews.activity.SecondaryPageActivity;
import com.example.admin.goodnews.adapter.DistrictNewsDataAdapter;
import com.example.admin.goodnews.adapter.XRecyclerViewAdapter;
import com.example.admin.goodnews.entity.DistrictNewsDataEntity;
import com.example.admin.goodnews.entity.GoodNewsDataEntity;
import com.example.admin.goodnews.entity.WeatherDataEntity;
import com.example.admin.goodnews.fragment.XinWenFenLei.CaiJingJiaoDianFragment;
import com.example.admin.goodnews.interfaces.RecyclerViewItemClickListener;
import com.example.admin.goodnews.interfaces.RecyclerViewItemLongClickListener;
import com.example.admin.goodnews.utils.GetCurrentTimeUtil;
import com.example.admin.goodnews.utils.HttpUtils;
import com.example.admin.goodnews.utils.NetWorkDataUrl;
import com.example.admin.goodnews.utils.StartActivityForResultUtils;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import static com.example.admin.goodnews.R.id.cardview_weather;


/**
 * 地区新闻页面
 * Created by admin on 2016/10/10.
 */

public class DiQuXinWenFragment extends Fragment implements RecyclerViewItemClickListener, RecyclerViewItemLongClickListener {
    private LinearLayout relativelayout_district;// 用于显示SnackBar
    private ImageView iv_district_weatherpic;// 天气图片
    private TextView tv_district_city;// 当前城市
    private TextView tv_district_province;// 当前城市所属的省份
    private TextView tv_district_temperature;// 当前城市的温度
    private TextView tv_district_weather;// 当前城市的天气情况
    private TextView tv_district_pm;// 当前城市的PM指数
    private TextView tv_district_weatherquality;// 当前城市的空气质量
    private TextView tv_district_winddirection;// 当前城市的风向
    private TextView tv_district_windpower;// 当前城市的风力
    private Button btn_district_changecity;// 切换城市按钮
    private XRecyclerView xrecyclerview_district;// 加载数据的容器
    private WeatherDataEntity weatherDataEntity;// 天气数据实体类
    private List<DistrictNewsDataEntity.ShowapiResBodyBean.PagebeanBean.ContentlistBean> datalists = new ArrayList<>();// 适配器需要的数据列表
    private List<DistrictNewsDataEntity.ShowapiResBodyBean.PagebeanBean.ContentlistBean> lists = new ArrayList<>();// 存放临时数据的列表
    private DistrictNewsDataAdapter districtNewsDataAdapter;// 数据适配器
    private LinearLayoutManager linearLayoutManager;// 布局管理器
//    private TextView tv_district_name;// 地区新闻

    private String city;// 城市名，用于请求省份和省份新闻数据
    private String area = "郑州";// 用于请求天气数据
    private String areaname;// 省份名，用于请求省份新闻数据
    private String time = GetCurrentTimeUtil.getCurrentTime();
    private int page = 1;// 页数，用于上拉加载和下拉刷新

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_diquxinwen, null);
        //relativelayout_district = (LinearLayout) view.findViewById(R.id.relativelayout_district);// 用于显示SnackBar
        iv_district_weatherpic = (ImageView) view.findViewById(R.id.iv_district_weatherpic);// 天气图片
        tv_district_city = (TextView) view.findViewById(R.id.tv_district_city);// 当前城市
        tv_district_province = (TextView) view.findViewById(R.id.tv_district_province);// 当前城市所属的省份
        tv_district_temperature = (TextView) view.findViewById(R.id.tv_district_temperature);// 当前城市的温度
        tv_district_weather = (TextView) view.findViewById(R.id.tv_district_weather);// 当前城市的天气情况
        tv_district_pm = (TextView) view.findViewById(R.id.tv_district_pm);// 当前城市的PM指数
        tv_district_weatherquality = (TextView) view.findViewById(R.id.tv_district_weatherquality);// 当前城市的空气质量
        tv_district_winddirection = (TextView) view.findViewById(R.id.tv_district_winddirection);// 当前城市的风向
        tv_district_windpower = (TextView) view.findViewById(R.id.tv_district_windpower);// 当前城市的风力
        btn_district_changecity = (Button) view.findViewById(R.id.btn_district_changecity);// 切换城市按钮
//        tv_district_name = (TextView) view.findViewById(R.id.tv_district_name);
        xrecyclerview_district = (XRecyclerView) view.findViewById(R.id.xrecyclerview_district);// 加载数据的容器

        // 设置布局管理器
        linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        xrecyclerview_district.setLayoutManager(linearLayoutManager);
        // 设置xrecyclerview_district不获取焦点
        xrecyclerview_district.setFocusable(true);
        // 下拉刷新和上拉加载
        xrecyclerview_district.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getDistrict();
            }

            @Override
            public void onLoadMore() {
                page++;
                getDistrict();
            }
        });
        getDistrict();
        getWeatherData();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 切换城市按钮点击事件
        btn_district_changecity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChangeCityActivity.class);
                startActivityForResult(intent, StartActivityForResultUtils.REQUESTCODE_FOR_CITY);
            }
        });
    }

    // 获取天气数据
    private void getWeatherData() {
        String param = NetWorkDataUrl.DISTRICT_PARAM1 + area + NetWorkDataUrl.DISTRICT_PARAM2 + time + NetWorkDataUrl.DISTRICT_PARAM3;
        try {
            HttpUtils.doPostAsyn(NetWorkDataUrl.DISTRICT_URL, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    weatherDataEntity = gson.fromJson(result, WeatherDataEntity.class);
                    if (weatherDataEntity != null) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //Snackbar.make(relativelayout_district, "服务器君离家出走了~", Snackbar.LENGTH_SHORT).show();
                    break;
                case 1:
                    // 加载天气图片
                    Picasso.with(getActivity()).load(weatherDataEntity.getShowapi_res_body().getNow().getWeather_pic()).into(iv_district_weatherpic);// 加载天气图片
                    // 设置当前城市
                    tv_district_city.setText("当前城市：" + weatherDataEntity.getShowapi_res_body().getCityInfo().getC5());
                    // 设置当前城市所属的省份
                    tv_district_province.setText("所属省份：" + weatherDataEntity.getShowapi_res_body().getCityInfo().getC7());
                    // 设置当前城市的温度
                    tv_district_temperature.setText("温度：" + weatherDataEntity.getShowapi_res_body().getNow().getTemperature() + "℃");
                    // 设置当前城市的天气情况
                    tv_district_weather.setText("天气：" + weatherDataEntity.getShowapi_res_body().getNow().getWeather());
                    // 设置当前城市的PM指数
                    tv_district_pm.setText("PM指数：" + weatherDataEntity.getShowapi_res_body().getNow().getAqiDetail().getPm2_5());
                    // 设置当前城市的空气质量
                    tv_district_weatherquality.setText("空气质量：" + weatherDataEntity.getShowapi_res_body().getNow().getAqiDetail().getQuality());
                    // 设置当前城市的风向
                    tv_district_winddirection.setText("风向：" + weatherDataEntity.getShowapi_res_body().getNow().getWind_direction());
                    // 设置当前城市的风力
                    tv_district_windpower.setText("风力：" + weatherDataEntity.getShowapi_res_body().getNow().getWind_power());
                    // 获取城市所属的省份，用于请求省份新闻数据
                    areaname = weatherDataEntity.getShowapi_res_body().getCityInfo().getC7();
//                    tv_district_name.setText(areaname + "新闻");
                    getDistrict(areaname);
                    break;
                case 2:
                    if (page == 1) {
                        datalists.clear();
                        datalists.addAll(lists);
                        districtNewsDataAdapter = new DistrictNewsDataAdapter(getActivity(), datalists);// 初始化适配器
                        xrecyclerview_district.setAdapter(districtNewsDataAdapter);// 给RecyclerView设置适配器
                        xrecyclerview_district.refreshComplete();
                        lists.clear();
                    } else {
                        datalists.addAll(lists);
                        districtNewsDataAdapter.notifyDataSetChanged();
                        xrecyclerview_district.loadMoreComplete();
                        lists.clear();
                    }
                    districtNewsDataAdapter.setRecyclerViewItemClickListener(DiQuXinWenFragment.this);
                    districtNewsDataAdapter.setRecyclerViewItemLongClickListener(DiQuXinWenFragment.this);
                    break;
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == StartActivityForResultUtils.REQUESTCODE_FOR_CITY && resultCode == StartActivityForResultUtils.RESULTCODE_FOR_CITY) {
            city = data.getExtras().get("city").toString();
            String url = NetWorkDataUrl.DISTRICT_URL;
            String param = NetWorkDataUrl.DISTRICT_PARAM1 + city + NetWorkDataUrl.DISTRICT_PARAM2 + GetCurrentTimeUtil.getCurrentTime() + NetWorkDataUrl.DISTRICT_PARAM3;
            try {
                HttpUtils.doPostAsyn(url, param, new HttpUtils.CallBack() {
                    @Override
                    public void onRequestComplete(String result) {
                        Gson gson = new Gson();
                        weatherDataEntity = gson.fromJson(result, WeatherDataEntity.class);
                        if (weatherDataEntity != null) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(0);
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 获取地区新闻数据
    private void getDistrict() {
        String param = NetWorkDataUrl.DISTRICTNEWS_PARAM1 + areaname + NetWorkDataUrl.DISTRICTNEWS_PARAM2 + page + NetWorkDataUrl.DISTRICTNEWS_PARAM3 + time + NetWorkDataUrl.DISTRICTNEWS_PARAM4;
        try {
            HttpUtils.doPostAsyn(NetWorkDataUrl.DISTRICTNEWS_URL, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    lists = gson.fromJson(result, DistrictNewsDataEntity.class).getShowapi_res_body().getPagebean().getContentlist();
                    if (lists.size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取地区新闻数据
    private void getDistrict(String areaname) {
        String param = NetWorkDataUrl.DISTRICTNEWS_PARAM1 + areaname + NetWorkDataUrl.DISTRICTNEWS_PARAM2 + page + NetWorkDataUrl.DISTRICTNEWS_PARAM3 + time + NetWorkDataUrl.DISTRICTNEWS_PARAM4;
        try {
            HttpUtils.doPostAsyn(NetWorkDataUrl.DISTRICTNEWS_URL, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    lists = gson.fromJson(result, DistrictNewsDataEntity.class).getShowapi_res_body().getPagebean().getContentlist();
                    if (lists.size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void RecyclerViewItemClickListener(int position) {
        String link = datalists.get(position).getLink();
        String title = datalists.get(position).getAreaName() + "新闻";
        Intent intent = new Intent(getActivity(), SecondaryPageActivity.class);
        intent.putExtra("link", link);
        intent.putExtra("title", title);
        startActivity(intent);
    }

    @Override
    public void RecyclerViewItemLongClickListener(int position) {
        String link = datalists.get(position).getLink();
        String title = datalists.get(position).getAreaName() + "新闻";
        Intent intent = new Intent(getActivity(), SecondaryPageActivity.class);
        intent.putExtra("link", link);
        intent.putExtra("title", title);
        startActivity(intent);
    }

}
